<template>
  <div class="app-container">
    <div class="app-card">
      <div v-loading="loading">
        <!-- 我的配送路线信息 -->
        <el-empty v-if="!hasRoute" description="您当前未被分配到任何配送路线"></el-empty>
        
        <div v-else>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card shadow="hover" class="route-info-card">
                <div slot="header" class="clearfix">
                  <span class="card-title">我的配送路线</span>
                  <el-tag :type="routeInfo.route.status === 1 ? 'success' : 'info'" size="medium">
                    {{ routeInfo.route.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </div>
                <div class="route-info">
                  <h3>{{ routeInfo.route.name }}</h3>
                  <p>{{ routeInfo.route.description }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <el-card shadow="hover">
                <div slot="header" class="clearfix">
                  <span class="card-title">配送进度</span>
                </div>
                <el-steps :active="currentStepIndex" finish-status="success" align-center>
                  <el-step 
                    v-for="(item, index) in routeInfo.items || []" 
                    :key="index" 
                    :title="item.leaderName"
                    :description="item.leaderAddress"
                    :status="getStepStatus(index)"
                  >
                    <template slot="icon">
                      <div class="custom-step-icon" :class="{'current-step': isCurrentLeader(item)}">
                        {{ index + 1 }}
                      </div>
                    </template>
                  </el-step>
                </el-steps>
              </el-card>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <el-card shadow="hover">
                <div slot="header" class="clearfix">
                  <span class="card-title">配送路线详情</span>
                </div>
                <el-table :data="routeInfo.items || []" border style="width: 100%">
                  <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
                  <el-table-column prop="leaderName" label="团长" width="120"></el-table-column>
                  <el-table-column prop="leaderPhone" label="联系电话" width="150"></el-table-column>
                  <el-table-column prop="leaderAddress" label="配送地址"></el-table-column>
                  <el-table-column label="状态" width="100" align="center">
                    <template slot-scope="scope">
                      <el-tag v-if="isCurrentLeader(scope.row)" type="danger">当前位置</el-tag>
                      <el-tag v-else-if="getItemIndex(scope.row) < currentStepIndex" type="success">已配送</el-tag>
                      <el-tag v-else-if="getItemIndex(scope.row) > currentStepIndex" type="info">待配送</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <el-card shadow="hover">
                <div slot="header" class="clearfix">
                  <span class="card-title">待配送订单</span>
                  <el-button type="text" @click="refreshOrders">刷新</el-button>
                </div>
                <el-table v-loading="ordersLoading" :data="pendingOrders" border style="width: 100%">
                  <el-table-column prop="orderNo" label="订单编号" width="300"></el-table-column>
                  <el-table-column prop="totalAmount" label="金额" width="300">
                    <template slot-scope="scope">
                      ¥{{ scope.row.totalAmount }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="300">
                    <template slot-scope="scope">
                      <el-tag :type="getOrderStatusType(scope.row.status)">
                        {{ getOrderStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" width="300"></el-table-column>
                  <el-table-column label="操作" align="center" width="300">
                    <template slot-scope="scope">
                      <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
                      <el-button 
                        v-if="scope.row.status === 1" 
                        type="warning" 
                        size="mini" 
                        @click="handleDeliver(scope.row)">配送
                      </el-button>
                      <el-button 
                        v-if="scope.row.status === 2" 
                        type="success" 
                        size="mini" 
                        @click="handleComplete(scope.row)">完成
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="pendingOrders.length === 0" class="empty-data">
                  <i class="el-icon-info"></i>
                  <span>暂无待配送订单</span>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="50%">
      <div v-loading="detailLoading">
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单编号">{{ orderDetail.order ? orderDetail.order.orderNo : '' }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="orderDetail.order ? getOrderStatusType(orderDetail.order.status) : ''">
              {{ orderDetail.order ? getOrderStatusText(orderDetail.order.status) : '' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总金额">¥ {{ orderDetail.order ? orderDetail.order.totalAmount : '' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ orderDetail.order ? orderDetail.order.createTime : '' }}</el-descriptions-item>
        </el-descriptions>

        <el-table
          :data="orderDetail.items || []"
          border
          fit
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="商品名称" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.productName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" width="120">
            <template slot-scope="scope">
              <span>¥ {{ scope.row.productPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.quantity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center" width="120">
            <template slot-scope="scope">
              <span>¥ {{ scope.row.subtotal }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRouteByLeaderId } from '@/api/delivery-route'
import { getLeaderOrders, getOrder, updateOrderStatus } from '@/api/order'

export default {
  name: 'LeaderDelivery',
  data() {
    return {
      loading: false,
      hasRoute: false,
      routeInfo: {
        route: {},
        items: []
      },
      leaderId: null,
      currentStepIndex: 0,
      pendingOrders: [],
      ordersLoading: false,
      dialogVisible: false,
      detailLoading: false,
      orderDetail: {
        order: null,
        items: []
      }
    }
  },
  created() {
    this.leaderId = Number(localStorage.getItem('leaderId'))
    this.getMyRouteInfo()
    this.getPendingOrders()
  },
  methods: {
    getMyRouteInfo() {
      this.loading = true
      
      // 使用新的API接口，直接根据团长ID获取路线信息
      getRouteByLeaderId(this.leaderId).then(response => {
        // 根据后端返回的数据结构调整
        if (response && response.route) {
          this.hasRoute = true
          this.routeInfo = {
            route: response.route || {},
            items: response.items || []
          }
          
          // 计算当前团长在路线中的位置
          if (this.routeInfo.items && this.routeInfo.items.length > 0) {
            this.currentStepIndex = this.routeInfo.items.findIndex(item => item.leaderId === this.leaderId);
            if (this.currentStepIndex === -1) this.currentStepIndex = 0;
          }
        } else {
          this.hasRoute = false
          this.routeInfo = {
            route: {},
            items: []
          }
          this.currentStepIndex = 0;
        }
        this.loading = false
      }).catch(error => {
        console.error('获取配送路线失败:', error)
        this.loading = false
        this.hasRoute = false
        this.routeInfo = {
          route: {},
          items: []
        }
        this.currentStepIndex = 0;
      })
    },
    getPendingOrders() {
      this.ordersLoading = true
      
      // 获取团长的待处理和配送中的订单
      const params = {
        status: null,
        page: 0,
        size: 50 // 获取足够多的订单
      }
      
      getLeaderOrders(this.leaderId, params).then(response => {
        if (response && response.records) {
          // 筛选出待处理和配送中的订单
          this.pendingOrders = response.records.filter(order => order.status === 1 || order.status === 2);
        } else if (Array.isArray(response)) {
          // 兼容旧版API返回格式
          this.pendingOrders = response.filter(order => order.status === 1 || order.status === 2);
        } else {
          this.pendingOrders = [];
        }
        this.ordersLoading = false
      }).catch(error => {
        console.error('获取待配送订单失败:', error)
        this.ordersLoading = false
        this.pendingOrders = []
      })
    },
    refreshOrders() {
      this.getPendingOrders()
    },
    isCurrentLeader(item) {
      return item.leaderId === this.leaderId
    },
    getItemIndex(item) {
      if (!this.routeInfo || !this.routeInfo.items) return -1;
      return this.routeInfo.items.findIndex(i => i.leaderId === item.leaderId);
    },
    getStepStatus(index) {
      if (this.getItemIndex({ leaderId: this.leaderId }) === index) {
        return 'process';
      } else if (index < this.currentStepIndex) {
        return 'finish';
      } else if (index > this.currentStepIndex) {
        return 'wait';
      }
      return '';
    },
    getOrderStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '已处理',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知'
    },
    getOrderStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'primary',
        2: 'warning',
        3: 'success',
        4: 'danger'
      }
      return typeMap[status] || ''
    },
    handleDetail(row) {
      this.dialogVisible = true
      this.detailLoading = true
      getOrder(row.id).then(response => {
        this.orderDetail = response || { order: null, items: [] }
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    // 配送订单
    handleDeliver(row) {
      this.$confirm('确认将订单标记为配送中?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 2).then(() => {
          this.$message.success('订单已开始配送')
          this.getPendingOrders()
        }).catch(() => {
          this.$message.error('操作失败')
        })
      }).catch(() => {})
    },
    // 完成订单
    handleComplete(row) {
      this.$confirm('确认将订单标记为已完成?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 3).then(() => {
          this.$message.success('订单已完成')
          this.getPendingOrders()
        }).catch(() => {
          this.$message.error('操作失败')
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.route-info-card {
  .card-title {
    font-size: 16px;
    font-weight: bold;
  }
  
  .route-info {
    h3 {
      margin-top: 0;
      margin-bottom: 10px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
    }
  }
}

.custom-step-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #C0C4CC;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  
  &.current-step {
    background-color: #F56C6C;
    box-shadow: 0 0 10px rgba(245, 108, 108, 0.5);
    transform: scale(1.1);
  }
}

.empty-data {
  padding: 30px;
  text-align: center;
  color: #909399;
  
  i {
    font-size: 30px;
    margin-right: 10px;
    vertical-align: middle;
  }
  
  span {
    font-size: 16px;
    vertical-align: middle;
  }
}
</style> 